from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
from PIL import Image
import cgi


class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD': 'POST',
                     'CONTENT_TYPE': self.headers['Content-Type'],
                     })

        # 假设我们接收的图片是通过'image'字段发送的
        image_field = form['image']
        if image_field and image_field.filename:
            # 读取图片数据
            image_data = image_field.file.read()
            # 将图片数据转换为BytesIO，以便PIL库可以处理
            image_bytes = BytesIO(image_data)
            # 使用PIL库保存图片
            image = Image.open(image_bytes)
            image.save('received_image.jpg', 'JPEG')

            # 返回响应
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(b'Image received successfully')
        else:
            self.send_error(400, 'No image found in the request')


if __name__ == '__main__':
    httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
    print("Serving at http://localhost:8000")
    httpd.serve_forever()